<script setup lang="ts">
import { useTokenStore } from '@/store/token'

// 页面配置
definePage({
  style: {
    navigationBarTitleText: '消息中心',
    navigationBarBackgroundColor: '#ffffff',
    navigationBarTextStyle: 'black',
  },
})

const tokenStore = useTokenStore()

// 定义消息类型
interface MessageItem {
  id: string
  type: 'notification' | 'private' | 'system' | 'comment'
  title: string
  content: string
  sender?: string
  avatar?: string
  time: string
  unread: boolean
  tag?: string
}

// 消息分类
const messageTypes = [
  { id: 'all', name: '全部', icon: 'icon-list' },
  { id: 'notification', name: '通知', icon: 'icon-bell' },
  { id: 'private', name: '私信', icon: 'icon-comment' },
  { id: 'system', name: '系统', icon: 'icon-settings' },
]

// 当前选中的分类
const selectedType = ref('all')
// 消息列表数据
const messageList = reactive<MessageItem[]>([])
// 加载状态
const loading = ref(false)
// 是否还有更多数据
const hasMore = ref(true)
// 当前页码
const currentPage = ref(1)
// 每页条数
const pageSize = 20

// 获取模拟消息数据
function getMockMessages(page: number, type?: string): MessageItem[] {
  const types = ['notification', 'private', 'system', 'comment'] as const
  const senders = ['系统管理员', '张三', '李四', '王五', '系统通知']
  const avatars = ['/static/logo.svg', '', '', '', '']
  const tags = ['重要', '活动', '提醒', '新功能', '']

  return Array.from({ length: pageSize }, (_, index) => {
    const msgType = type === 'all' ? types[Math.floor(Math.random() * types.length)] : (type as any)
    const id = `${msgType}-${page}-${index}`
    const randomSenderIndex = Math.floor(Math.random() * senders.length)

    // 根据消息类型生成不同的内容
    let title = ''
    let content = ''

    switch (msgType) {
      case 'notification':
        title = '活动通知'
        content = '您有一个新的活动邀请，点击查看详情。'
        break
      case 'private':
        title = senders[randomSenderIndex]
        content = `您好，我想咨询一下关于专家服务的问题，请问您方便吗？`
        break
      case 'system':
        title = '系统通知'
        content = '系统将于明天凌晨2点进行维护升级，预计持续2小时。'
        break
      case 'comment':
        title = '评论回复'
        content = `${senders[randomSenderIndex]} 回复了您的评论：非常感谢您的解答！`
        break
    }

    // 生成时间
    const now = new Date()
    const hoursAgo = Math.floor(Math.random() * 48)
    const messageTime = new Date(now.getTime() - hoursAgo * 60 * 60 * 1000)
    const formattedTime = `${messageTime.getHours().toString().padStart(2, '0')}:${
      messageTime.getMinutes().toString().padStart(2, '0')}`

    // 模拟未读状态，前几页的消息有较高概率未读
    const isUnread = page === 1 && Math.random() > 0.3

    return {
      id,
      type: msgType,
      title,
      content,
      sender: msgType === 'private' || msgType === 'comment' ? senders[randomSenderIndex] : undefined,
      avatar: msgType === 'private' || msgType === 'comment' ? avatars[randomSenderIndex] : undefined,
      time: formattedTime,
      unread: isUnread,
      tag: Math.random() > 0.7 ? tags[Math.floor(Math.random() * tags.length)] : undefined,
    }
  }).filter(item => type === 'all' || item.type === type)
}

// 加载消息列表
async function loadMessages(refresh = false) {
  // 如果已经没有更多数据，则不再加载
  if (!hasMore.value && !refresh) {
    return
  }

  // 如果正在加载，则不再重复加载
  if (loading.value) {
    return
  }

  loading.value = true

  try {
    // 模拟网络请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))

    const page = refresh ? 1 : currentPage.value
    const newMessages = getMockMessages(page, selectedType.value)

    if (refresh) {
      // 下拉刷新时清空列表并重置状态
      messageList.splice(0, messageList.length)
      hasMore.value = true
      currentPage.value = 1
    }

    // 添加新消息
    messageList.push(...newMessages)

    // 判断是否还有更多数据
    hasMore.value = newMessages.length === pageSize

    // 更新当前页码
    if (newMessages.length > 0 && !refresh) {
      currentPage.value++
    }
  }
  catch (error) {
    console.error('加载消息失败:', error)
    uni.showToast({ title: '加载消息失败', icon: 'error' })
  }
  finally {
    loading.value = false
    // 结束下拉刷新
    if (refresh) {
      uni.stopPullDownRefresh()
    }
  }
}

// 切换消息分类
function switchType(type: string) {
  if (selectedType.value === type) {
    return
  }

  selectedType.value = type
  // 切换分类时重新加载数据
  loadMessages(true)
}

// 查看消息详情
function viewMessageDetail(message: MessageItem) {
  // 标记消息为已读
  if (message.unread) {
    message.unread = false
  }

  // 跳转到消息详情页
  uni.navigateTo({
    url: `/pages/message/detail?id=${message.id}&type=${message.type}&title=${encodeURIComponent(message.title)}`,
  })
}

// 获取未读消息总数
const unreadCount = computed(() => {
  return messageList.filter(msg => msg.unread).length
})

// 计算过滤后的消息列表
const filteredMessages = computed(() => {
  return selectedType.value === 'all' ? messageList : messageList.filter(msg => msg.type === selectedType.value)
})

// 计算当前分类的未读消息数
const currentTypeUnreadCount = computed(() => {
  if (selectedType.value === 'all') {
    return unreadCount.value
  }
  return messageList.filter(msg => msg.type === selectedType.value && msg.unread).length
})

// 页面加载时初始化数据
onLoad(() => {
  loadMessages()
})

// 页面显示时检查登录状态
// onShow(() => {
//   if (!tokenStore.isLogin) {
//     uni.showToast({ title: '请先登录', icon: 'none' })
//     setTimeout(() => {
//       uni.redirectTo({ url: '/pages/login/index' })
//     }, 1000)
//   }
// })

// 设置下拉刷新
// uni.setEnablePullDownRefresh({ enable: true })

// // 监听下拉刷新事件
// uni.onPullDownRefresh(() => {
//   loadMessages(true)
// })

// // 监听上拉触底事件
// uni.onReachBottom(() => {
//   if (!loading.value && hasMore.value) {
//     loadMessages()
//   }
// })
</script>

<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 消息分类标签 -->
    <view class="sticky top-0 z-10 bg-white shadow-sm">
      <view class="scrollbar-hide flex overflow-x-auto">
        <view
          v-for="type in messageTypes"
          :key="type.id"
          class="flex-shrink-0 px-4 py-3 text-center"
          @click="switchType(type.id)"
        >
          <view
            class="text-base font-medium transition-colors"
            :class="selectedType === type.id ? 'text-blue-500' : 'text-gray-600'"
          >
            {{ type.name }}
          </view>
          <view
            v-if="(selectedType === 'all' && unreadCount > 0)
              || (selectedType === type.id && currentTypeUnreadCount > 0)"
            class="mx-auto mt-1 h-4 w-4 flex items-center justify-center rounded-full bg-red-500 text-[10px] text-white"
          >
            {{ selectedType === 'all' ? unreadCount : currentTypeUnreadCount }}
          </view>
          <view
            v-else
            class="mx-auto mt-1 h-4 w-4 rounded-full"
          />
          <view
            v-if="selectedType === type.id"
            class="mx-auto mt-1 h-0.5 w-10 rounded-full bg-blue-500"
          />
        </view>
      </view>
    </view>

    <!-- 消息列表 -->
    <view class="pb-6">
      <view
        v-for="message in filteredMessages"
        :key="message.id"
        class="relative mx-4 mt-3 overflow-hidden rounded-lg bg-white shadow-sm transition-all hover:shadow-md"
        @click="viewMessageDetail(message)"
      >
        <!-- 未读标记 -->
        <view v-if="message.unread" class="absolute left-4 top-1/2 h-2 w-2 rounded-full bg-red-500 -translate-y-1/2" />

        <!-- 消息内容 -->
        <view class="flex gap-4 p-4">
          <!-- 头像 -->
          <view v-if="message.avatar" class="h-10 w-10 flex-shrink-0 overflow-hidden rounded-full bg-gray-100">
            <image :src="message.avatar" mode="aspectFill" class="h-full w-full" />
          </view>
          <view v-else class="h-10 w-10 flex flex-shrink-0 items-center justify-center rounded-full bg-gray-100">
            <text class="text-gray-500">{{ message.title.charAt(0) }}</text>
          </view>

          <!-- 消息主体 -->
          <view class="min-w-0 flex-1">
            <view class="mb-1 flex items-center justify-between">
              <view class="flex items-center gap-2">
                <text class="text-gray-800 font-medium">{{ message.title }}</text>
                <view v-if="message.tag" class="rounded bg-blue-500 px-1.5 py-0.5 text-xs text-white">
                  {{ message.tag }}
                </view>
              </view>
              <text class="text-xs text-gray-400">{{ message.time }}</text>
            </view>
            <text class="line-clamp-2 text-sm text-gray-600">{{ message.content }}</text>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="filteredMessages.length === 0 && !loading" class="mt-20 text-center">
        <image src="/static/logo.svg" alt="" class="mx-auto mb-4 h-20 w-20 opacity-30" />
        <view class="text-gray-500">
          暂无消息
        </view>
        <view class="mt-2 text-sm text-gray-400">
          {{ selectedType === 'all' ? '暂无任何消息' : `暂无${messageTypes.find(t => t.id === selectedType)?.name}消息` }}
        </view>
      </view>

      <!-- 加载中 -->
      <view v-if="loading" class="flex justify-center p-6">
        <!-- <uni-loading type="circle" size="24"></uni-loading> -->
        <text class="ml-2 text-sm text-gray-500">加载中...</text>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!hasMore && filteredMessages.length > 0" class="py-4 text-center text-sm text-gray-400">
        没有更多消息了
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
/* 使用了UNOCSS原子化类名，无需额外样式 */
.scrollbar-hide::-webkit-scrollbar {
  display: none;
}
</style>
